//
//  AddressManageViewController.m
//  ShrimpCrowdordering
//
//  Created by 郑洲 on 2018/7/26.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "AddressManageViewController.h"

#import "AddAddressViewController.h"
#import "AddressTableViewCell.h"
#import "AppDelegate.h"
#import "AddressManagerModel.h"

@interface AddressManageViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) BaseTableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic,strong)  AddressManagerModel   * addressManagerModel;

@end

@implementation AddressManageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"收货地址管理";
    self.view.backgroundColor = RGB_COLOR(244, 244, 244);
    self.dataArray = [NSMutableArray array];
    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT - ScreenX375(49))];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = ScreenX375(119);
    [self.view addSubview:self.tableView];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - ScreenX375(49) - NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, ScreenX375(49))];
    [button setTitle:@"  新建地址" forState:UIControlStateNormal];
    [button setTitleColor:REXADECIMALCOLOR(@"#ffffff") forState:UIControlStateNormal];
    button.titleLabel.font = Kfont(18);
    [button setImage:[UIImage imageNamed:@"联系人"] forState:UIControlStateNormal];
    [button setBackgroundImage:ImageWithName(@"按钮背景") forState:UIControlStateNormal];
    [button addTarget:self action:@selector(addAddress) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    [self getData];
    
    [kNotificationCenter addObserver:self selector:@selector(getData) name:@"ReloadAddressList" object:nil];
}

- (void)dealloc {
    [kNotificationCenter removeObserver:self name:@"ReloadAddressList" object:nil];
}

- (void)getData {
    NSDictionary *parameter = @{@"id":kNSUDefaultReadKey(@"userId")};
    [HttpManager postHttpRequestByGet:[NSString stringWithFormat:@"%@api/getUserAddress",REQUESTHEADER] andParameter:parameter success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        if ([status isEqualToString:@"200"]) {
            [self.dataArray removeAllObjects];
            NSError *error = nil;
            for (NSDictionary *dict in successResponse[@"data"][@"list"]) {
                AddressManagerModel *model = [[AddressManagerModel alloc] initWithDictionary:dict error:&error];
                [self.dataArray addObject:model];
            }
            [self.tableView reloadData];
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

- (void)addAddress {
    AddAddressViewController *vc = [[AddAddressViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AddressTableViewCell *cell = [AddressTableViewCell cellWithTableView:tableView andIndexPath:indexPath];
    AddressManagerModel *model = _dataArray[indexPath.section];
    cell.addressModel = model;
    
    cell.editClick = ^{
        AddAddressViewController *vc = [[AddAddressViewController alloc] init];
        vc.addressModel = model;
        [self.navigationController pushViewController:vc animated:YES];
    };
    cell.deleteClick = ^{
        NSString * url = [NSString stringWithFormat:@"%@api/deleteUserAddress",REQUESTHEADER];
        NSDictionary * parameter = @{@"id":model.Id};
        [HttpManager showWait];
        [HttpManager postHttpRequestByPost:url andParameter:parameter success:^(id successResponse) {
            [self.tableView.mj_header endRefreshing];
            NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
            if ([status isEqualToString:@"200"]) {
                [HttpManager showNoteMsg:@"删除成功"];
                [self.dataArray removeObjectAtIndex:indexPath.row];
                [self.tableView reloadData];
            }else{
                [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
            }
        } andFailure:^(id failureResponse) {
            [HttpManager showFail];
        }];
    };
    cell.selectClick = ^{
        NSInteger isDefault = 1;
        if ([model.isDefault integerValue] == 1) {
            isDefault = 0;
        }
        NSString * url = [NSString stringWithFormat:@"%@api/updateUserAddress",REQUESTHEADER];
        NSDictionary * parameter = @{@"userId":kNSUDefaultReadKey(@"userId"),@"recProvince":model.recProvince,@"recCity":model.recCity,@"recArea":model.recArea,@"recAddress":model.recAddress,@"recName":model.recName,@"recPhone":model.recPhone,@"isDefault":[NSString stringWithFormat:@"%@",[NSNumber numberWithBool:isDefault]],@"id":model.Id};
        [HttpManager showWait];
        [HttpManager postHttpRequestByPost:url andParameter:parameter success:^(id successResponse) {
            [self.tableView.mj_header endRefreshing];
            [HttpManager hideWait];
            NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
            if ([status isEqualToString:@"200"]) {
                [kNotificationCenter postNotificationName:@"ReloadAddressList" object:self userInfo:nil];
            }else{
                [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
            }
        } andFailure:^(id failureResponse) {
            [HttpManager showFail];
        }];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return ScreenX375(10);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(10))];
    view.backgroundColor = RGB_COLOR(244, 244, 244);
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_isSelect) {
        AddressManagerModel *model = [self.dataArray objectAtIndex:indexPath.section];
        [_delegate passValue:model];
        [self.navigationController popViewControllerAnimated:YES];
    }
    if (_isFromUnity) {
//        AddressManagerModel *model = _dataArray[indexPath.section];
//        NSString *addressStr = [NSString stringWithFormat:@"%@,%@%@%@%@,%@,%@",model.Id,model.recProvince,model.recCity,model.recArea,model.recAddress,model.recName,model.recPhone];
//        const char * str =[addressStr UTF8String];
//        UnitySendMessage("DontDestory", "SaveAddress", str);
//        AppDelegate *delegate = (AppDelegate *)kAppDelegate;
//        [delegate showUnityWindow];
//        UnityPause(false);
//        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
